package com.hltx.controller.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.user.User;
import com.hltx.pojo.user.UserAccount;
import com.hltx.service.order.OrderManager;
import com.hltx.service.user.UserManager;
import com.hltx.service.user.UserVipManager;
import com.hltx.util.ResultInfo;

/**
 * 用户controller
 * 
 * @author
 *
 */
@Controller
public class UserVipController extends BaseController {

	@Autowired
	private UserVipManager userVipService;

	@Resource(name = "userService")
	private UserManager userService;
	
	@Resource(name="orderService")
	private OrderManager orderService;
	
	@Value("${domain}")
	private String domain;
	
	/**
	 * session 域获取user对象
	 * @param session
	 * @return
	 */
	private static User getUser(HttpSession session) {
		User user = (User) session.getAttribute("sessionUser");
		return user;
	}

	/**
	 * 打开个人中心
	 */
	@RequestMapping("/user/myvip")
	public String index(HttpServletRequest request, HttpSession session) {
		User u = getUser(session);

		User us = new User();
		us.setId(u.getId());
		User user = userService.getUser(us);
		if(user !=null){
			String codePre = user.getCodePre();
			String codeSuf = user.getCodeSuf();
			String loginId = user.getId()+"";   
			String vipcode = codePre+loginId+codeSuf;  //定义用户唯一的标识 用于二维码和邀请
			session.setAttribute("vipcode", vipcode);
		}
		request.setAttribute("user", user);
		request.setAttribute("domain", domain);
		return "user/my_vip";
	}
	
	/**
     * vip升级条款
     */
	@RequestMapping("/user/myvip/regulation")
	public String vipRegulation(HttpServletRequest request, HttpSession session) {
		return "user/vip_regulation";
	}
	
    /**
     * 升级vip
     */
	@RequestMapping("/user/myvip/upVip")
	@ResponseBody
	public Map<String, Object> upVip(HttpServletRequest request, HttpSession session){
		this.logBefore(logger, "升级VIP");
		Map<String, Object> params=new HashMap<>();
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		User user = getUser(session); // 获取当前用户
		if(user!=null){
			params.put("userId", user.getId());
			String needMoney=request.getParameter("needMoney");
			String level=request.getParameter("level");
			String oldLevel=request.getParameter("oldLevel");
			params.put("needMoney", needMoney);
			params.put("level", level);
			params.put("oldLevel", oldLevel);
			ResultInfo resultInfo=userVipService.upVipLevel(params);
			resMap.put("result", this.initResult(resultInfo.getState(), resultInfo.getCode(), resultInfo.getMessage()));
		}}catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 前往我的好友页面
	 * 
	 * @return
	 */
	@RequestMapping("/user/myvip/myfriend")
	public String friend(HttpServletRequest request, HttpSession session) {
	/*	Map<String, Map<String, String>> size = userVipService.getSize();
		String subor = size.get("subor").get("value"); // 获取下级好友的范围
		session.setAttribute("subor", subor);*/
		return "user/friends";
	}

	/**
	 * 我的好友页面——数据展示
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/user/myvip/friends", method = { RequestMethod.POST })
	public Map<String, Object> myFriend(Page page, Integer ids,Integer key, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "查询我的好友列表");
		Map<String, Object> resMap = new HashMap<String, Object>();

		try {
			User user = getUser(session); // 获取当前用户
			int id = user.getId();
			
			if (ids == 0 || ids == null || id == ids) {
				
				User u = userVipService.getUserById(id);   //获取  用户信息
				resMap.put("user", u.getPetName());
				List<User> lowerUserList = userVipService.getMyFriendLowerList(id); // 获取下级的好友列表
				resMap.put("parentId", 0);
				resMap.put("lul", lowerUserList);
				int count = userVipService.getFriendCount(id); // 获取下级好友的个数
				resMap.put("count", count);
			} else {
				User u = userVipService.getUserById(ids);  //获取  用户信息
				resMap.put("user", u.getPetName());
				
				int parentId = userVipService.getParentId(ids);
				List<User> lowerUserList = userVipService.getMyFriendLowerList(ids); // 获取下级的好友列表
				resMap.put("lul", lowerUserList);
				resMap.put("parentId", parentId);
				int count = userVipService.getFriendCount(ids); // 获取下级好友的个数
				resMap.put("count", count);
			}
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}

	/**
	 * 前往vip升级页面
	 * 
	 * @return
	 */
	@RequestMapping("/user/myvip/toupgradevip")
	public String toUpgradeVip(HttpServletRequest request, HttpSession session) {
		return "user/vipup";
	}

	/**
	 * 用户升级vip 的数据展示
	 */
	@RequestMapping(value = "/myvip/upgrade", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> saveUpgradeVIP(HttpServletRequest request, HttpSession session) {
		this.logBefore(logger, "vip升级");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			    User user = getUser(session); // 获取当前的用户
			    if(user!=null){
			    	UserAccount userAccount=userVipService.getUserAccount(user.getId());
					resMap.put("user", user);
					resMap.put("userAccount", userAccount);
					String level=userVipService.getUserLevel(user);
					resMap.put("level", level);
			    }
				List<Map<String, Object>> vipAllLevel = userVipService.getVIPLevelALL();// 获取所有的等级信息
				resMap.put("vipAllLevel", vipAllLevel);
	            resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}

	@RequestMapping("/user/myvip/autonym")
	public String autonym(HttpServletRequest request,HttpSession session,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception {
//		PrintWriter out = null;
//		response.setCharacterEncoding("utf-8");
//		out = response.getWriter();
//		String name = (String) params.get("name");
//		String code = (String) params.get("code");
//		User user = (User) session.getAttribute("sessionUser");
//		Integer id = user.getId();
//		String result=userService.getUser(id,name,code);
		return "user/realname";
	}
	
	/**
	 * to   我的返现     
	 */
	@RequestMapping("/user/myvip/cashback")
	public String cashback(HttpServletRequest request){
		return "user/rebate_list";
	}
	/**
	 * 我的返现    -- 数据展示 
	 */
	@RequestMapping(value = "/user/myvip/mycashback", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> mycashback(Page page, HttpServletRequest request,
			HttpSession session) {
		this.logBefore(logger, "我的返现的数据展示");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			User user = getUser(session);
			
			page.getParams().put("userid", user.getId());
			//获取订单列表
			List<Map<String, Object> > cashbackMap= userVipService.getOrderList(page);
			String mystate = (String) page.getParams().get("state");
			resMap.put("mystate", mystate);
			resMap.put("cashbackMap", cashbackMap);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
    /**
     * vip等级说明
     */
	@RequestMapping(value = "/user/myvip/Explain", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> Explain( HttpServletRequest request,HttpSession session) {
		this.logBefore(logger, "vip等级说明");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
	        String level=request.getParameter("level");
            String explain=userVipService.getVExplain(level);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", explain));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	/**
	 * 去充值页面
	 */
	@RequestMapping(value = "/user/myvip/goRecharge")
	public String goRecharge(HttpServletRequest request,HttpSession session) {
		this.logBefore(logger, "用户充值");
		try {
			User us = getUser(session); // 获取当前用户
			if(us!=null){
			UserAccount userAccount=userService.getAccount(String.valueOf(us.getId()));
			request.setAttribute("userAccount", userAccount);
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
		}
		this.logAfter(logger);
		return "user/vipRecharge";
	}
}
